<!DOCTYPE html>
<html>
    <head>
        <title>Edit User</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0 user-scalable=no">
        <link rel="stylesheet" href="../../script/semantic/semantic.css">
        <link rel="stylesheet" href="../../script/ao.css">
        <script type="text/javascript" src="../../script/jquery.min.js"></script>
        <script type="text/javascript" src="../../script/semantic/semantic.js"></script>
        <script type="text/javascript" src="../../script/ao_module.js"></script>
        <style>
            body{
                background-color:white;
            }
            .themebackground{
                background-color:#588ce0 !important;
                color:white !important;
                background-image: url("/img/public/slate.png") !important;
                background-repeat: no-repeat !important;
                background-attachment: fixed !important;
                height:100px;
                border: 0px solid transparent !important;
                padding:24px !important;
            }
            .required{
                color:red;
            }
            .actionbtns{
                text-align:right;
            }
        </style>
    </head>
    <body>
        <div class="ui fluid attached segment themebackground" >
            <h24 class="ui inverted header">
                <i class="edit icon"></i>
                <div class="content">
                    Edit User
                <div class="sub header">Edit user profile and permissions</div>
                </div>
            </h4>
        </div>
        <div class="ui container">
            <div id="confirmUpdate" class="ui green inverted segment" style="display:none; margin-top:12px;">
                <i class="checkmark icon"></i> Profile Updated
            </div>
            <div id="updateError" class="ui red inverted segment" style="display:none; margin-top:12px;">
                <i class="remove icon"></i> <span id="errmsg"></span>
            </div>
            <h4>User Profile & Permission</h4>
            <form class="ui form" onsubmit="handleUserProfileUpdate(event);">
                <div class="field">
                  <label>Username</label>
                  <input id="username" type="text" name="username" placeholder="Username" readonly=true>
                </div>
                <div class="field">
                    <div class="ui divder"></div>
                    <label>Permission Groups</label>
                    <select id="pgroups" multiple="" class="ui fluid dropdown">
                        
                    </select>
                </div>

                <table class="ui celled table">
                    <thead>
                        <tr><th>Group Name</th>
                        <th>Is Admin</th>
                        <th>Accessible Modules</th>
                    </tr></thead>
                    <tbody id="permissionTable">
                        
                    </tbody>
                </table>

                <div class="two fields">
                    <div class="field">
                        <label>Storage Quota <span class="required">*</span></label>
                        <input id="quota" type="text" value="15">
                        <small>Set to 0 for READONLY and -1 for Unlimited Storage</small>
                    </div>
                    <div class="field">
                        <label>Unit <span class="required">*</span></label>
                        <select class="ui fluid search dropdown" id="unit">
                            <option value="1">Bytes</option>
                            <option value="1024">KB</option>
                            <option value="1048576">MB</option>
                            <option value="1073741824">GB</option>
                            <option value="1099511627776">TB</option>
                            <option value="1125899906842624">PB</option>
                            </select>
                    </div>
                </div>
                
                <button class="ui right floated button" onclick="event.preventDefault(); handleEditorExit();">Close</button>
                <button class="ui primary right floated button" type="submit">Update</button>
                <br><br>
                <div class="ui divider"></div>
                <h4>Password & Security</h4>
                <p>Reset Password</p>
                <button class="ui red button" onclick="restartPassword();">RESET PASSWORD</button>
                <p>A temporary password will be generated once reset is requested. Administrator should provide the user with the password reset link generated below for the user to reset their password.</p>
                <div id="tmppwui" class="ui green segment" style="margin-top:12px; display:none;">
                    <p><i class="checkmark icon"></i> Password Reset Link Generated</p>
                    <div class="ui labeled fluid input">
                        <label for="tmpw" class="ui label"><i class="key icon"></i></label>
                        <input id="tmppw" type="text" placeholder="Temporary Password" id="tmpw">
                      </div>
                      <small>Please provide the password reset link listed above to the user and request user to update their password through the password reset tool.</small>
                </div>
       
            </div>
        <script>
            var currentEditingUsername = "";
            var userdata;
            var groupList = {};
            //Get username from window hash
            if (window.location.hash.length > 0){
                var username = window.location.hash.substring(1);
                username = decodeURIComponent(username);
                $("#username").val(username);
                currentEditingUsername = username;
            }
            
            $("#pgroups").on("change", function(e){
                updatePGTable();
            });

            $("#unit").dropdown("set selected","GB");
            function bytesToSize(bytes) {
                var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];
                if (bytes == 0) return '0 Byte';
                var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
                return [bytes / Math.pow(1024, i), sizes[i]];
            }

            initContents(function(){
                initGroupList(function(){
                    $('.ui.dropdown').dropdown();
                });
            });

            function handleEditorExit(){
                ao_module_parentCallback(true);
                ao_module_close();
            }

            function initContents(callback=undefined){
                //Update the table contents
                $.ajax({
                    url: "../../system/users/editUser",
                    data: {username: currentEditingUsername},
                    method:"POST",
                    success: function(data){
                        if (data.error !== undefined){
                            alert(data.error);
                        }else{
                            userdata = data;
                            var displaysize = bytesToSize(data.Quota)
                            
                            if (data.Quota == -1){
                                //Unlimited
                                $("#quota").val(-1);
                            }else if (data.Quota == -2){
                                //Not initialized. Set it to 0
                                $("#quota").val(0);
                            }else{
                                $("#quota").val(displaysize[0]);
                            }
                            
                            $("#unit").dropdown("set selected",displaysize[1])
                            if (callback !== undefined){
                                callback();
                            }
                        }
                    }
                });
            }

            function initGroupList(callback=undefined){
                //Initialize group list
                $.ajax({
                    url: "../../system/permission/listgroup?showper=true",
                    success: function(data){
                        $("#pgroups").html("");
                        if (data.error !== undefined){
                            alert(data.error)
                        }else{
                            groupList = data;
                            for (const [key, value] of Object.entries(data)) {
                                $("#pgroups").append(`<option value="${key}">${key}</option>`);
                            }
                            $('#pgroups').dropdown('set selected', userdata.Usergroup);
                            updatePGTable();

                            if (callback !== undefined){
                                callback();
                            }
                            
                        }
                        
                    }
                });
            }

            function updatePGTable(){
                $("#permissionTable").html("");
                var pgList = $("#pgroups").val();
                pgList.forEach(pgid => {
                    var groupInfo = groupList[pgid];
                    var isAdmin = '<i class="green checkmark icon"></i>';
                    if (groupInfo[1] == false){
                        isAdmin = '<i class="red remove icon"></i>';
                    }
                    $("#permissionTable").append(`
                        <tr>
                            <td data-label="groupname">${pgid}</td>
                            <td data-label="isdamin">${isAdmin}</td>
                            <td data-label="modules">${groupInfo[0].join("/")}</td>
                        </tr>`);
                });

            }

            function restartPassword(){
                var username = $("#username").val();
                $.ajax({
                    url: "../../system/users/editUser",
                    data: {opr: "resetPassword", username: username},
                    method: "POST",
                    success: function(data){
                        if (data.error !== undefined){
                            alert(data.error);
                        }else{
                            //Update suceed
                            initContents();
                            $("#confirmUpdate").stop().finish().slideDown('fast').delay(3000).slideUp('fast');
                            console.log(data);
                            $("#tmppw").val(location.protocol + '//' + location.host + "/reset.system?acc=" + username +  "&rkey=" + data);
                            $("#tmppwui").slideDown('fast');
                        }
                    }
                });
            }

            function handleUserProfileUpdate(e){
                e.preventDefault();
                //Get all the value from the form
                var username = $("#username").val();
                var pgs = JSON.stringify($("#pgroups").val());
                
                //Parse Quota
                var userStorageQuota = parseFloat($("#quota").val()) * $("#unit").val();
                if (isNaN(userStorageQuota)){
                    $("#quota").parent().addClass("error");
                    return
                }else{
                    $("#quota").parent().removeClass("error");
                }

                if (parseInt($("#quota").val()) == -1){
                    userStorageQuota = -1;
                }
                
                $.ajax({
                    url: "../../system/users/editUser",
                    data: {opr: "updateUserGroup", newgroup: pgs, username: username, quota: userStorageQuota},
                    method: "POST",
                    success: function(data){
                        if (data.error !== undefined){
                            $("#errmsg").text(data.error);
                            $("#updateError").stop().finish().slideDown('fast').delay(3000).slideUp('fast');
                        }else{
                            //Update suceed
                            initContents();
                            updatePGTable();
                            $("#confirmUpdate").stop().finish().slideDown('fast').delay(3000).slideUp('fast');
                            ao_module_parentCallback(true);

                        }
                        window.scrollTo(0,0);
                    }
                });
            }

           
        </script>
    </body>
</html>